<?php

namespace App\Helpers;

use Symfony\Component\HttpFoundation\Response as FoundationResponse;

trait ApiResponse
{
    /**
     * @var int
     */
    protected $statusCode = FoundationResponse::HTTP_OK;

    /**
     * @return mixed
     */
    public function getStatusCode()
    {
        return $this->statusCode;
    }

    /**
     * @param $statusCode
     * @return $this
     */
    public function setStatusCode($statusCode)
    {

        $this->statusCode = $statusCode;
        return $this;
    }

    /**
     * @param $data
     * @param array $header
     * @return mixed
     */
    public function respond($data, $header = [])
    {
        return response()->json($data, $this->getStatusCode(), $header);
    }

    /**
     * @param $status
     * @param array $data
     * @param null $code
     * @return mixed
     */
    public function status(array $data, $code = null)
    {
        if ($code) {
            $this->setStatusCode($code);
        }
        return $this->respond($data);
    }

    /**
     * @param $message
     * @param int $code
     * @param string $status
     * @return mixed
     */
    public function failed($errcode, $message = null)
    {
        $errcode = is_null($errcode) ? 'common-error' : $errcode;
        $error = config('errcode.' . $errcode);
        $message = $message ?? $error['message'];
        return $this->setStatusCode($error['statusCode'])->status([
            'code' => $error['code'],
            'message' => $message
        ]);
    }

    /**
     * @param $message
     * @param string $status
     * @return mixed
     */
    public function message($message, $code = null)
    {
        $errcode = is_null($code) ? 1000 : $code;
        return $this->status([
            'code' => $errcode,
            'message' => $message
        ], $code);
    }

    /**
     * @param string $message
     * @return mixed
     */
    public function internalError($message = "服务器内部错误")
    {
        return $this->message($message, Foundationresponse::HTTP_INTERNAL_SERVER_ERROR);
    }

    /**
     * @param $data
     * @param string $status
     * @return mixed
     */
    public function success($data)
    {
        $code = 1000;
        return $this->status(compact('data', 'code'));
    }

    /**
     * @param string $message
     * @return mixed
     */
    public function notFound($message = '该模型未找到')
    {
        return $this->message($message, Foundationresponse::HTTP_NOT_FOUND);
    }

    public function resource($resource)
    {
        return $resource->additional(['code' => 1000]);
    }
}
